//
//  EvaluateOrderViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/9/8.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "AFNetworking.h"

#import "EvaluateFooterView.h"
#import "EvaluateOrderCell.h"
#import "EvaluateOrderSubmitModel.h"

#import "EvaluateOrderViewController.h"

@interface EvaluateOrderViewController ()<UITableViewDelegate, UITableViewDataSource, TZImagePickerControllerDelegate>

@property (nonatomic, strong) NSMutableArray <EvaluateOrderSubmitModel *>*submitArray;

@end

@implementation EvaluateOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self prepareData];
    [self initView];
}

- (void)prepareData {
    
    //订单拼参
    if (self.model) {
        for (int i = 0; i < self.model.userOrderGoodList.count; i++) {
            EvaluateOrderSubmitModel *submitModel = [[EvaluateOrderSubmitModel alloc] init];
            
            submitModel.imageUrls = @[].mutableCopy;
            CommonMediaModel *imgModel = [[CommonMediaModel alloc] init];
            imgModel.url = @"";
            [submitModel.imageUrls addObject:imgModel];
            
            submitModel.ueEvaluateContent = @"从多个角度评价宝贝，可以帮助更多想买的人~";
            submitModel.ueEvaluateStar = 5.0f;
            
            if (self.model.userOrderGoodList[i].ogGoodsType == 2) {
                submitModel.ueGoodsId = self.model.userOrderGoodList[i].goodsId;
            } else {
                submitModel.ueGoodsId = self.model.userOrderGoodList[i].ogGoodsId;
            }
            
            [self.submitArray addObject:submitModel];
        }
    }
    
    //预约拼参
    if (self.subscribeModel) {
        
        EvaluateOrderSubmitModel *submitModel = [[EvaluateOrderSubmitModel alloc] init];
        
        submitModel.imageUrls = @[].mutableCopy;
        CommonMediaModel *imgModel = [[CommonMediaModel alloc] init];
        imgModel.url = @"";
        [submitModel.imageUrls addObject:imgModel];
        
        submitModel.ueEvaluateContent = @"从多个角度评价店铺，可以帮助更多需要服务的人~";
        submitModel.ueEvaluateStar = 5.0f;
        [self.submitArray addObject:submitModel];

    }
    
    if (self.subscribeRingModel) {
        EvaluateOrderSubmitModel *submitModel = [[EvaluateOrderSubmitModel alloc] init];
        
        submitModel.imageUrls = @[].mutableCopy;
        CommonMediaModel *imgModel = [[CommonMediaModel alloc] init];
        imgModel.url = @"";
        [submitModel.imageUrls addObject:imgModel];
        
        submitModel.ueEvaluateContent = @"从多个角度评价宝贝，可以帮助更多想买的人";
        submitModel.ueEvaluateStar = 5.0f;
        [self.submitArray addObject:submitModel];
    }
}

- (void)initView {
    
    self.title = @"发表评论";
    
    UIButton *publishBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    publishBtn.frame = CGRectMake(0,0,52,24);
    publishBtn.layer.cornerRadius = 12.0f;
    [publishBtn setBackgroundColor:UIColorHex(0xFF4242)];
    publishBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [publishBtn setTitle:@"提交" forState:UIControlStateNormal];
    [publishBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [publishBtn addTarget:self action:@selector(publishAction) forControlEvents:UIControlEventTouchUpInside];
    
    [publishBtn.widthAnchor constraintEqualToConstant:52].active =YES;
    [publishBtn.heightAnchor constraintEqualToConstant:24].active =YES;
    
    UIBarButtonItem *publishItem = [[UIBarButtonItem alloc] initWithCustomView:publishBtn];

    self.navigationItem.rightBarButtonItems =@[publishItem];
    
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableview.backgroundColor =  UIColorHex(0xffffff);
    
    self.tableview.showsHorizontalScrollIndicator = NO;
    self.tableview.showsVerticalScrollIndicator = NO;
    
    self.tableview.estimatedSectionHeaderHeight = 0;
    self.tableview.estimatedSectionFooterHeight = 0;
    self.tableview.estimatedRowHeight = 0;
    
    [self.tableview registerNib:[UINib nibWithNibName:@"EvaluateOrderCell" bundle:nil] forCellReuseIdentifier:@"EvaluateOrderCellID"];
    
    [self.tableview reloadData];
}

#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.submitArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 300;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 5;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [UIView new];
    view.backgroundColor = UIColorHex(0xffffff);
    return view;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    EvaluateFooterView *footerView  =  [[NSBundle mainBundle] loadNibNamed:@"EvaluateFooterView"owner:nil options:nil].firstObject;

    [footerView fillFooterWithModel:self.submitArray[section]];
    
    WEAKSELF
    footerView.EvaluateFooterViewActionBlock = ^(EvaluateFooterViewActionType type, CGFloat score, NSInteger index, NSString * _Nonnull content) {
      
        switch (type) {
            case EvaluateFooterViewActionType_star:{
                
                weakSelf.submitArray[section].ueEvaluateStar = score;
                [weakSelf.tableview reloadData];
            } break;
            case EvaluateFooterViewActionType_content:{
                
                self.submitArray[section].ueEvaluateContent = content;
                
            } break;
            case EvaluateFooterViewActionType_addPhoto:{
                //添加图片
                [weakSelf uplodPhotoWithSection:section];

            } break;
            case EvaluateFooterViewActionType_delPhoto:{
                //删除图片
                [weakSelf delPhotoWithSection:section AndIndex:index];

            } break;
            default:
                break;
        }
        
    };
    
    return footerView;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    EvaluateOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EvaluateOrderCellID"];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    
    if (self.model) {
        [cell fillCellWithModel:self.model.userOrderGoodList[indexPath.section]];
    }
    
    if (self.subscribeModel) {
        [cell fillCellWithSubscribeModel:self.subscribeModel];
    }
    
    if (self.subscribeRingModel) {
        [cell fillCellWithSubscribeRingModel:self.subscribeRingModel];
    }
    
    return cell;
}

//publishAction
- (void)publishAction {
    for (EvaluateOrderSubmitModel *model in self.submitArray) {
        
        if ([model.ueEvaluateContent isEqualToString:@"从多个角度评价宝贝，可以帮助更多想买的人"] ||
            [model.ueEvaluateContent isEqualToString:@"从多个角度评价店铺，可以帮助更多需要服务的人~"] ||
            [model.ueEvaluateContent isEqualToString:@"从多个角度评价宝贝，可以帮助更多想买的人~"] ||
            model.ueEvaluateContent.length == 0) {
            
            [SVProgressHUD showErrorWithStatus:@"评价内容最少十个字哦"];
            [SVProgressHUD dismissWithDelay:1];
            return;
        }
        
    }
    
    [self request_submitEvaluate];
}


- (NSMutableArray<EvaluateOrderSubmitModel *> *)submitArray {
    if (!_submitArray) {
        _submitArray = @[].mutableCopy;
    }
    return _submitArray;
}

- (void)delPhotoWithSection:(NSInteger)section AndIndex:(NSInteger)index {
    //删掉对应的
    [self.submitArray[section].imageUrls removeObjectAtIndex:index];
    
    if (self.submitArray[section].imageUrls.count == 0) {
        CommonMediaModel *imgModel = [[CommonMediaModel alloc] init];
        imgModel.url = @"";
        [self.submitArray[section].imageUrls addObject:imgModel];
    }
    
    [self.tableview reloadData];    
}

- (void)uplodPhotoWithSection:(NSInteger)section {

    NSInteger count = 9;
    TZImagePickerController *vc = [[TZImagePickerController alloc]
                                   initWithMaxImagesCount:count delegate:self];

    vc.naviBgColor = default_color_white;
    vc.naviTitleColor = default_color_black;
    vc.barItemTextColor = default_color_black;

    vc.photoWidth = 2048.0f;
    
    vc.preferredLanguage = @"zh-Hans";

    //筛选到只剩图片
    vc.allowPickingVideo = NO;
    vc.allowPickingMultipleVideo = NO;
    vc.allowPickingGif = NO;
    vc.allowPickingVideo = NO;

    vc.showSelectedIndex = YES;
    vc.showSelectBtn = YES;

    //裁剪
    vc.allowCrop = YES;
    vc.cropRect = CGRectMake( 0 ,(TTScreenHeight - TTScreenWidth)/2, TTScreenWidth, TTScreenWidth);

    WEAKSELF
    [vc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
        // 准备保存结果的数组，元素个数与上传的图片个数相同，先用 NSNull 占位
        NSMutableArray* result = [NSMutableArray array];
        for (int i = 0; i < photos.count; i++) {
            [result addObject:[NSNull null]];
        }
        
        dispatch_group_t group = dispatch_group_create();

        [SVProgressHUD showWithStatus:@"正在上传评价图片"];
        for (NSInteger i = 0; i < photos.count; i++)
        {
            dispatch_group_enter(group);
            dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                
                // ContentType设置
                AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
                manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"image/jpeg",@"image/png",@"application/octet-stream",@"text/json",nil];
                manager.requestSerializer= [AFHTTPRequestSerializer serializer];
                manager.responseSerializer= [AFHTTPResponseSerializer serializer];
                [manager.requestSerializer setValue:[TTUserModel sharedObject].token forHTTPHeaderField:@"token"];
                
                // 上传完整地址
                NSString * urlString = [NSString stringWithFormat:@"%@headImgUpload",TT_Global_Service_Domain];
                
                [manager POST:urlString parameters:nil headers:@{} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                            
                    if (photos[i] != nil) {
                    NSData *data = UIImageJPEGRepresentation(photos[i], 0.2f);
                    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                    formatter.dateFormat = @"yyyyMMddHHmmss";
                    NSString *str = [formatter stringFromDate:[NSDate date]];
                    NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
                    [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/jpg"];
                    }
                    
                } progress:^(NSProgress * _Nonnull uploadProgress) {
                    NSLog(@"%.2f",uploadProgress.fractionCompleted);

                } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

                    NSString *resultStr = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];

                    if ([resultStr isKindOfClass:[NSString class]]) {
                        
                        @synchronized (result) {
                            result[i] = resultStr;
                        }
                    }
                    dispatch_group_leave(group);
                    
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    dispatch_group_leave(group);

                }];
            });
           
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue(), ^{
            NSLog(@"上传完成!");
            [SVProgressHUD showSuccessWithStatus:@"上传成功"];
            [SVProgressHUD dismissWithDelay:0.5];

            weakSelf.submitArray[section].imageUrls = @[].mutableCopy;
            for (int i = 0; i < result.count; i++) {
                NSString *imgStr = result[i];

                if ([imgStr isKindOfClass:[NSString class]]) {
                    
                    CommonMediaModel *model = [[CommonMediaModel alloc] init];
                    model.url = imgStr;
                    [weakSelf.submitArray[section].imageUrls addObject:model];
                    [weakSelf.tableview reloadData];
                }
            }
        });
    }];

    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)request_submitEvaluate {

    self.handleBtn.userInteractionEnabled = NO;
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    NSMutableArray *evaluateVoList = @[].mutableCopy;

    for (int i = 0; i < self.submitArray.count; i++) {
        
        EvaluateOrderSubmitModel *submitModel = self.submitArray[i];
        NSMutableDictionary *evaluateVo = [submitModel modelToJSONObject];
        
        NSMutableArray *imageUrls = @[].mutableCopy;
        for (int j = 0; j < submitModel.imageUrls.count; j++) {
            
            CommonMediaModel *mediaModel = submitModel.imageUrls[j];
            NSMutableDictionary *mediaDic = [mediaModel modelToJSONObject];

            [imageUrls addObject:mediaDic];
        }
        [evaluateVo setValue:imageUrls forKey:@"imageUrls"];

        [evaluateVoList addObject:evaluateVo];
    }
    
    [dic setValue:evaluateVoList forKey:@"evaluateVoList"];
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"ueEvaluateUserId"];
    
    if (self.model) {
        [dic setValue:@"2" forKey:@"ueEvaluateSource"];
        [dic setValue:self.model.uodOrderId forKey:@"ueOrderId"];
        [dic setValue:self.model.uodSellerId forKey:@"ueSellerId"];
    }
    
    if (self.subscribeModel) {
        [dic setValue:@"1" forKey:@"ueEvaluateSource"];
        [dic setValue:self.subscribeModel.seller.sellerId forKey:@"ueSellerId"];
        [dic setValue:self.subscribeModel.cdId forKey:@"cdId"];
    }
    
    if (self.subscribeRingModel) {
        [dic setValue:@"1" forKey:@"ueEvaluateSource"];
        [dic setValue:self.subscribeRingModel.sellerId forKey:@"ueSellerId"];
        [dic setValue:self.subscribeRingModel.abId forKey:@"abId"];
    }

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_OrderEvaluate];

    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {

                [SVProgressHUD showSuccessWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
                [weakSelf.navigationController popViewControllerAnimated:YES];
                
            } else {

                weakSelf.handleBtn.userInteractionEnabled = YES;

                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }

    } FailedBlock:^(NSError * _Nonnull error) {
        weakSelf.handleBtn.userInteractionEnabled = YES;
    }];

}




@end
